package com.itheima.controller;

import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import com.itheima.utils.MyThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 部门管理Controller
 */
@RestController
@Slf4j
@RequestMapping("/depts")
public class DeptController {
    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result selectAll(){
        log.debug("我们自己写的日志....................................");
        List<Dept> depts = deptService.selectAll();
        Map<String,Object> value= MyThreadLocalUtils.getValue();
        System.out.println("从ThreadLocal中获取的令牌解析的结果是:==============" +
                "=================================="+value);
        return Result.success(depts);
    }

    @DeleteMapping("/{id}")
    public Result delById(@PathVariable Integer id){
        int i=deptService.delById(id);

        return i>=1?Result.success("ok"):Result.error(id+"为的部门删除失败,请确认id后重试!");
    }

    @PostMapping
    public Result saveDept(@RequestBody Dept dept){
        int i=deptService.insertDept(dept);
        return i>=1?Result.success(dept.getId()):Result.error("添加部门:"+dept.getName()+"失败,请确认数据后重试!");

    }

    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id){
        Dept dept = deptService.selectById(id);
        return dept!=null?Result.success(dept):Result.error("id为:"+id+"的部门不存在");
    }

    @PutMapping
    public Result updateDept(@RequestBody Dept dept){
        int i = deptService.updateDept(dept);
        return i>0?Result.success(dept):Result.error("id为:"+dept.getId()+"的部门修改失败");
    }
}
